<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, This is user service.</title>
</head>
<body>
<h2>User - Login</h2>
<p>请输入用户名和密码（test/test），然后点击登录按钮。</p>

<table>
    <tbody>
    <tr>
        <td>User:</td>
        <td><input type="text" name="username" value=""></td>
    </tr>
    <tr>
        <td>Password:</td>
        <td><input type="password" name="password"></td>
    </tr>
    <tr>
        <td>Roles:</td>
        <td><input type="text" name="roles" value="ROLE_ADMIN"></td>
    </tr>
    <tr>
        <td colspan="2">
            <button id="btn_login">登录</button>
        </td>
    </tr>
    </tbody>
</table>

<ol>
    <li><a href="http://localhost:9002/index.html">UI Home</a></li>
    <li><a href="/logout.html">Logout</a></li>
    <li><a href="/">Go User Home</a></li>
</ol>

</body>

<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script>
<script type="text/javascript">

    $("#btn_login").click(function () {

        let userName = $("input[name='username']").val();
        let userPwd = $("input[name='password']").val();
        let userRole = $("input[name='roles']").val();

        if (userName == null || userName == "" || userPwd == null || userPwd == "") {
            alert("用户名和密码不能为空");
        } else {
            let data = {
                "userName": userName,
                "userPwd": userPwd,
                "userRole": userRole
            };

            $.ajax({
                url: "/api/login",
                type: "POST",
                data: JSON.stringify(data),
                processData: false,
                contentType: "application/json;charset=utf-8",
                success: function (data, status, ajax) {
                    console.log("succeeded to login.");
                    let userName = $.cookie("user_name");
                    let userRole = $.cookie("user_role");
                    alert("登录成功，用户信息保存到了cookie中。用户名：" + userName + ", 用户角色：" + userRole);

                    // redirect to callback url if there is specified in the query strings
                    let callback = qs("callback");
                    if (callback) {
                        window.location.replace(callback);
                    }
                },
                error: function () {
                    console.log("fail to login.");
                    alert("登录失败，请输入用户名和密码（test/test）");
                }
            });
        }

    });

    function qs(key) {
        key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
        var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
        return match && decodeURIComponent(match[1].replace(/\+/g, " "));
    }

</script>

</html>